/*
 * This servlet processes a file upload.
 */
package controllers.managecontrollers;
import classes.Breadcrumbs;
import classes.HibernateUtil;
import dao.FileDao;
import dao.LessonDao;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.Files;
import models.Lesson;
//Import the commons fileupload jar file and commons i/o
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Achie
 */
public class ManageFileController extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long id = System.nanoTime();
        String name;
        String type = "ordinary";
        String fileName = null;
        String url; //path of the file
        String path = "/uploads"; //folder where the file goes to
        //-----------------------------------------------------
        //Process the encoded form & save the file on the uploads folder
        //-----------------------------------------------------

        String folderLocation = request.getRealPath(path);
        System.out.println("Volledige url: " + folderLocation);
        HashMap<String, String> formParams = new HashMap<String, String>();
        // String fileName = null;
        FileItem i = null;
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        try {
            if (isMultipart) {

                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);

                // Parse the request
                List<FileItem> items = upload.parseRequest(request);

                // Process the uploaded items
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();

                    if (item.isFormField()) {
                        // Process a regular form field
                        formParams.put(item.getFieldName(), item.getString());
                        // fileName = request.getParameter("filename");
                    } else {
                        // Process a file upload
                        fileName = item.getName();
                        File uploadedFile = new File(folderLocation + File.separator + fileName);

                        if (formParams.get("edit") == null) { //add file 
                            i = item;
                            item.write(uploadedFile);
                        }

                        if (formParams.get("edit") != null) {  //edit file physically
                            //standby writing
                            if (formParams.get("overwrite") != null) {
                                //start writing
                                i = item;
                                item.write(uploadedFile);
                            }
                        }
                    }
                }
            }
        } catch (FileUploadException fue) {
            fue.printStackTrace();
            throw new ServletException(fue.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
        long lessonid = Long.parseLong(formParams.get("lessonid"));
        //-------------------------------------------------------------
        //Check whether the form is an edit
        //-------------------------------------------------------------
        if (formParams.get("edit") != null) { //if true, edit

            //-------------------
            //get file
            //-------------------
            HibernateUtil hu = new HibernateUtil();
            FileDao fd = new FileDao(hu.openSession());
            long fileid = Long.parseLong(formParams.get("fileid"));
            Files updatefile = fd.get(fileid);

            updatefile.setName(formParams.get("filename")); //update the file with the new name

            if (formParams.get("overwrite") != null) { //check whether the file will be overwritten
                updatefile.setFileName(fileName);
                updatefile.setUrl(path + "/" + fileName); //update the url 
            }

            if (formParams.get("isassignment") != null) { //check whether it is an assignment
                updatefile.setType("assignment"); //if it is, set type as assignment
            } else {
                updatefile.setType("ordinary");
            }

            String urlx = path + "/" + fileName; //set url

            if (formParams.get("overwrite") != null) { //check whether the file will be overwritten
                if (urlx.endsWith("docx") || urlx.endsWith("doc") || urlx.endsWith("pdf") || urlx.endsWith("txt") || urlx.endsWith("ppt") || urlx.endsWith("pptx")) {
                    if (i.getSize() > 10490000) { //max 10 mb
                        response.sendRedirect("ManageFileController/edit?edit=true&lessonid=" + lessonid + "&fileid=" + fileid);
                    } else {
                        fd.update(updatefile);
                        response.sendRedirect("FileController/view?id=" + lessonid);
                    }
                } else {
                    response.sendRedirect("ManageFileController/edit?edit=true&lessonid=" + lessonid + "&fileid=" + fileid);
                    request.setAttribute("errormessage", true);
                }
            } else {
                fd.update(updatefile); //update the file
                response.sendRedirect("FileController/view?id=" + lessonid); //redirect
            }
            return;
        }

        //------------------------------------------------------------------------------------------------------
        //Save the file url in the database containing the lesson and attributes
        //------------------------------------------------------------------------------------------------------

        name = formParams.get("filename");//Assign values to the variables

        if (formParams.get("isassignment") != null) {
            type = "assignment";
        }
        url = path + "/" + fileName;

        HibernateUtil hu = new HibernateUtil();
        //--------------------------------------------------------------
        //Save file
        //--------------------------------------------------------------
        //URL:
        //  System.out.println(request.getContextPath() + "" + url);
        FileDao fd = new FileDao(hu.openSession());
        Files doFile = new Files(id, name, type, url, fileName);


        //--------------------------------------------------------------
        //get lesson and save the file
        //--------------------------------------------------------------
        //response.sendRedirect(request.getContextPath() + "" + url);
        LessonDao ld = new LessonDao(hu.openSession());
        Lesson les = ld.get(lessonid);
        doFile.setLesson(les);

        if (url.endsWith("docx") || url.endsWith("doc") || url.endsWith("pdf") || url.endsWith("txt") || url.endsWith("ppt") || url.endsWith("pptx")) {
            if (i.getSize() > 10490000) {
                response.sendRedirect("ManageFileController/add?lessonid=" + lessonid);
            } else {
                fd.save(doFile);
                response.sendRedirect("FileController/view?id=" + lessonid);
            }
        } else {
            response.sendRedirect("ManageFileController/add?lessonid=" + lessonid);
            request.setAttribute("errormessage", true);
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    /*
     * This method prepares the add edit files jsp page
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HibernateUtil hu = new HibernateUtil();
        if (request.getParameter("edit") != null) { //file edit
            long lessonid = Long.parseLong(request.getParameter("lessonid"));
            long fileid = Long.parseLong(request.getParameter("fileid"));

            //get file object
            FileDao fd = new FileDao(hu.openSession());
            Files file = fd.get(fileid);

            request.setAttribute("filex", file);

            //get the lesson and set it as attribute
            LessonDao ld = new LessonDao(hu.openSession());
            Lesson l = ld.get(lessonid);
            request.setAttribute("lesson", l);

            //set the edit trigger as true
            request.setAttribute("edit", true);

            // Breadcrumbs
            Breadcrumbs[] breadcrumbs = {
                new Breadcrumbs("Index", "Home"),
                new Breadcrumbs("CourseLessonEdit", "Manage lessons"),
                new Breadcrumbs("FileController/view?id=" + lessonid, "Manage files"),
                new Breadcrumbs("ManageFileController/add?lessonid=" + lessonid, "Edit file")
            };
            request.setAttribute("breadcrumbs", breadcrumbs);

            RequestDispatcher dispatcher = request.getRequestDispatcher("../jsp/add_edit_files.jsp");
            dispatcher.forward(request, response);
        }

        if (request.getParameter("remove") != null) { //remove file
            long lessonid = Long.parseLong(request.getParameter("lessonid"));
            long fileid = Long.parseLong(request.getParameter("fileid"));


            FileDao fd = new FileDao(hu.openSession());
            Files fileToDelete = fd.get(fileid); //get the object to be removed
            fd.delete(fileToDelete); //delete the object
            response.sendRedirect("../FileController/view?id=" + lessonid);
        }

        if (request.getParameter("lessonid") != null && request.getParameter("edit") == null && request.getParameter("remove") == null) { //add new file
            long lessonid = Long.parseLong(request.getParameter("lessonid"));
            request.setAttribute("lessonid", lessonid);
            LessonDao ld = new LessonDao(hu.openSession());
            Lesson l = ld.get(lessonid);
            request.setAttribute("lesson", l);

            // Breadcrumbs
            Breadcrumbs[] breadcrumbs = {
                new Breadcrumbs("Index", "Home"),
                new Breadcrumbs("CourseLessonEdit", "Manage lessons"),
                new Breadcrumbs("FileController/view?id=" + lessonid, "Manage files"),
                new Breadcrumbs("ManageFileController/add?lessonid=" + lessonid, "Add file")
            };
            request.setAttribute("breadcrumbs", breadcrumbs);

            //redirect to the add edit files page
            RequestDispatcher dispatcher = request.getRequestDispatcher("../jsp/add_edit_files.jsp");
            dispatcher.forward(request, response);
        }
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
